package com.lyx.bookmanager.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lyx.bookmanager.mapper.BookMapper;
import com.lyx.bookmanager.mapper.GxUserBookCollectMapper;
import com.lyx.bookmanager.mapper.GxUserBookPayMapper;
import com.lyx.bookmanager.mapper.TradeInfoMapper;
import com.lyx.bookmanager.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author liuhaoqi
 * @Date 2022/5/12 15:01
 * @Version 1.0
 */
@Controller
public class PayController {

    @Autowired
    private TradeInfoMapper tradeInfoMapper;

    @Autowired
    private GxUserBookPayMapper gxUserBookPayMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private GxUserBookCollectMapper gxUserBookCollectMapper;

    //appid
    private final String APP_ID = "2021000119692568";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCWYxwCbAVxknsBsnKJaLXF82WlvDGFqMhW84k7AAw6GhxzQmOd3bRSn1bn49sNeXbNYOWovLl5VK57NjTBOpIY6TGrBkFtWnoiT/xFjclvZNZn90B4eXA7c8SRvtbhznzzew0cuZcmocAfd2/4H83QCXQTOA1Gd8Xpnq6QLnSvxSXq15sy7EOz1GxsHNdP+gsRdzcWkfHbtzl9AiFnm10/u6+Cr74QaWWfxkxZc/LUmn10+A/InlOPgBHG/TjYf5E8Yg/UNdyC/rnGs2R+TZleK2xLjzL4izW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tC37hgb6DCiSMzjAN55i7GTCmZ4x5HJFBCwKBgQCziiePQOjOTWeYVgfelEzzJ3nlKTCH7KbODP3APtjAsdBIuR9U9A+0J9Tmgf0LgM0KvTNNUbimoYo5kmX+gw5+6AcHZo/UIm92sU8Rx5M+AKgoPjKbQDUtpRGxxBV5t55bjLVZjoU9RtibBuCdUDbpNgWp6mlBuw6tNqlN9hvxMQ==";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkqMvhRD9NRGGyKhjd0y9bMCbVzaS9kboAqBLKdE9gsg3M2P4xXWej2pI9VJtuaUP5N4kNKdqW7grdE+nX3vuXAxaMwahYZMVFGaZIOyGmToWpFgZJDmxc1ENiNThFTrpxNNAtDqy9Iy/76n6onl3vdqkQAqZXb8Ukzze7UxWoyrg9PdlPruJTG1HjnjcKyPfll81dHLoT5xI0yN2WFAseT/ajEeLJZA35THWigRjWN8Cmg9xnnCznDukPAzQs+hZpo9brZVvd++eoX0ZZcTo4Phk4xc/pFlNz21UOBuj4iX/2MGB5eHXxLqgY7qWKoG6TSks2PLyteZl2P+WZ/ILXwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1:8080/user/book/getAll";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/returnUrl";

    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") float dona_money,
                        @RequestParam("bookid") String bookid,
                        @RequestParam("bookname") String bookname,
                         @RequestParam("username") String username) throws AlipayApiException {
        session.setAttribute("bookid", bookid);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,bookname);
    }

    /*
    参数1：订单号
    参数2：订单金额
    参数3：订单名称
     */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    @RequestMapping("/returnUrl")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session, Model model) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + money);

            //在这里编写自己的业务代码（对数据库的操作）
//            request.getParameter("")
            TradeInfo tradeInfo = new TradeInfo(out_trade_no, trade_no, money);
            tradeInfoMapper.insert(tradeInfo);
            String bookid = (String) session.getAttribute("bookid");
            String username = (String) session.getAttribute("username");
            System.out.println(bookid);
            System.out.println(username);
            long id = Long.parseLong(bookid);
            GxUserBookPay gxUserBookPay = new GxUserBookPay(Long.parseLong(username),id);

            gxUserBookPay.setCreateTime(new Date());
            gxUserBookPay.setUpdateTime(new Date());
            gxUserBookPayMapper.insert(gxUserBookPay);

            List<GxUserBookCollect> list = gxUserBookCollectMapper.getGxUserBookCollectList(id, username);
            Book book = bookMapper.getBookById(bookid);
            book.setIsBuy(1);
            book.setRemarkList(list);
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag", 1);
            model.addAttribute("msg", "支付成功");
            model.addAttribute("book", book);
            return "user/pay_tips";
        } else {
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag", 0);
            model.addAttribute("msg", "支付失败");
            String bookid = (String) session.getAttribute("bookid");
            Book book = bookMapper.getBookById(bookid);
            model.addAttribute("book", book);
            return "user/pay_tips";
        }
    }
}
